import React, { useState } from "react";
import "./index.less";
import { actions } from "./store";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import TableModal from "../../components/TableModal/TableModal";

function TableList({
  deleteAction,
  tableLists,
  upAction,
  downAction,
  addAction,
  isModalVisible,
}) {
  const [updataItem, setUpdataItem] = useState(null);

  function deleteItem(item, index) {
    deleteAction(index);
  }
  function upItem(item, index) {
    upAction(index);
  }
  function downItem(item, index) {
    downAction(index);
  }
  function addItem() {
    setUpdataItem({ updata: false });
    addAction();
  }
  function upDateItem(item, index) {
    setUpdataItem({ ...item, updata: true, index });
    addAction({ ...item, index: index });
  }
  function renderTableList() {
    return tableLists.map((item, index) => (
      <div className="list" key={item.id}>
        <div>
          <div>{item.name}</div>
          <div>{item.age}</div>
          <div>{item.address}</div>
        </div>
        <div className="list-btn">
          <button
            className={index == 0 ? "btn-up" : "btn"}
            onClick={() => {
              upItem(item, index);
            }}
          >
            上移
          </button>
          <button
            className={index == tableLists.length - 1 ? "btn-up" : "btn"}
            onClick={() => {
              downItem(item, index);
            }}
          >
            下移
          </button>
          <button
            className="btn"
            onClick={() => {
              upDateItem(item, index);
            }}
          >
            更新
          </button>
          <button
            className="btn"
            onClick={() => {
              deleteItem(item, index);
            }}
          >
            删除
          </button>
        </div>
      </div>
    ));
  }

  return (
    <div>
      <button onClick={addItem} className="btn-last">
        添加
      </button>
      <div>{renderTableList()}</div>
      <TableModal
        isModalVisible={isModalVisible}
        updataItem={updataItem}
      ></TableModal>
    </div>
  );
}

export default connect(
  (state) => {
    return state.tableListStore;
  },
  (dispatch) => {
    return bindActionCreators(actions, dispatch);
  }
)(TableList);
